package com.hrz.lib.rxmvpdemo2.contract.second;

import android.util.Log;

import com.hrz.lib.rxmvpdemo2.NetApi;
import com.hrz.lib.rxmvpdemo2.NewResponse;
import com.hrz.lib.rxmvpdemo2.bean.NewsBean;
import com.rxmvp.baselibrary.base.RxBasePresenter;
import com.rxmvp.baselibrary.base.RxHelper;
import com.rxmvp.baselibrary.base.mvp.IBaseView;
import com.rxmvp.baselibrary.rxbus.Events;
import com.rxmvp.baselibrary.rxbus.RxBus;
import com.rxmvp.baselibrary.rxretrofit.subscriber.BaseSubscriber;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 作者： huangRZ  日期： 2017/2/13. email：917647409@qq.com
 * Explain：
 */

public class SecondPresenter extends RxBasePresenter<SecondContract.IView, ActivityEvent> implements SecondContract.IPresenter {

    private NetApi api;
    private Disposable mDisposable;
    private Disposable mDisposable2;

    @Inject
    public SecondPresenter(IBaseView view, LifecycleProvider<ActivityEvent> activityLifecycleProvider,
                           RxHelper<ActivityEvent> rxUtils, NetApi api) {
        super(view, activityLifecycleProvider, rxUtils);
        this.api = api;
    }


    @Override
    public void onCreate() {
    }

    @Override
    public void onStart() {
        //在事件总线上订阅一个事件
        subscribe();
    }

    @Override
    public void onStop() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable2 != null){
            mDisposable2 = null;
        }
        if ((mDisposable != null)){
            mDisposable = null;
        }
    }

    private void subscribe() {
        if (mDisposable2 == null) {
            mDisposable2 = RxBus.with(mLifecycleProvider)
                    //设置subscriber跟随activity的destroy状态发生而解绑，避免subscriber的内存泄漏
                    .setLifecycleEvent(ActivityEvent.DESTROY)
                    //设置观察“事件总线”上的事件类型
                    .setEvent(Events.TAP)
                    //处理可能发生的错误
                    .onError(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            /**
                             * 笔记： 如果有异常发生，那么subscriber就会自动取消订阅，不再观察到事件的发生
                             */
                            Log.e("tag", "t : " + throwable.getMessage());
                            mView.showShortToast(throwable.getMessage());
                        }

                    })
                    //当该subscriber观察的事件发生时，会将事件的结果在这里处理
                    .onNext(new Consumer<Events<?>>() {
                        @Override
                        public void accept(Events<?> events) {
//                        NewsBean newsBean = (NewsBean) events.getContent();
//                        textView.setText(newsBean.toString());
                            mView.setText((String) events.getContent());
                        }
                    })
                    ._create();
        }
    }

    //发送一个事件
    public void sendEvent() {
        //利用retrofit+RxJava完成网络异步访问获取数据
        mDisposable = mRxHelper.setLifecycleEvent(ActivityEvent.DESTROY)
                .getFlowable(api.getJson("yule", "004a2b29ab3245fdfb95ed25e590cc2b"), mLifecycleProvider)
                .map(new Function<NewResponse<NewsBean>, String>() {
                    @Override
                    public String apply(NewResponse<NewsBean> newsBeanBaseResponse) {
                        //将网络获取的数据转换成一个泛型为String的observer，传递下去
                        return newsBeanBaseResponse.getResult().getData().get(0).toString();
                    }
                })
                .subscribeWith(new BaseSubscriber<String>(){

                    @Override
                    public void onSuccess(String response) {
                        //创建一个事件对象，包括事件类型和事件内容（数据）
                        Events<String> stringEvents = new Events<>();
                        stringEvents.setCode(Events.TAP);
                        stringEvents.setContent(response);
                        //将事件发送到事件总线上，订阅了该事件的subscriber将会观察到到该数据
                        RxBus.getInstance().send(stringEvents);
                    }

                    @Override
                    protected void onStart() {
                        super.onStart();
                        mView.showPB();
                    }

                    @Override
                    public void onFailure() {
                        mView.hidePB();
                        mView.setText("获取数据失败");
                    }

                    @Override
                    public void onComplete() {
                        mView.hidePB();
                    }
                });
    }

}
